This page was automatically generated by NetLogo 5.0.5.

The applet requires Java 5 or higher. Java must be enabled in your browser settings. Mac users must have Mac OS X 10.4 or higher. Windows and Linux users may obtain the latest Java from Oracle's Java site.


In order for this to work, this file, your model file (SymbiosisModelFOR APPLET.nlogo), and the files NetLogoLite.jar and NetLogoLite.jar.pack.gz must all be in the same directory. (You can copy NetLogoLite.jar and NetLogoLite.jar.pack.gz from the directory where you installed NetLogo.)

The applet will also need access to the gis and nw extensions. Copy the entire directory for each required extension into the same directory as the applet.

On some systems, you can test the applet locally on your computer before uploading it to a web server. It doesn't work on all systems, though, so if it doesn't work from your hard drive, please try uploading it to a web server.

You don't need to include everything in this file in your page. If you want, you can just take the HTML code beginning with <applet> and ending with </applet>, and paste it into any HTML file you want. It's even OK to put multiple <applet> tags on a single page.

If the NetLogoLite files and your model are in different directories, you must modify the archive= and value= lines in the HTML code to point to their actual locations. (For example, if you have multiple applets in different directories on the same web server, you may want to put a single copy of the NetLogoLite files in one central place and change the archive= lines of all the HTML files to point to that one central copy. This will save disk space for you and download time for your users.)

powered by NetLogo

view/download model file: SymbiosisModelFOR APPLET.nlogo

WHAT IS IT?

This model is applied to a case study exploring at the development of regional Industrial symbiosis around the agricultural-based product industry in the Champagne-Ardenne region (France) where a circular supply chain initiative, limited to the flow circulation of cereals and beats waste and by-products, is already in place (see Figure 19). Champagne-Ardenne is a European crossroad lying on the main roads from Paris to Germany and from the UK or Belgium to the south of France, where over 60 percent of its land is dedicated to agriculture (crops, livestock farming and vineyards). Here, we envision that this local circular supply chain initiative can be extended to become an IS endeavor that goes beyond the agriculture industry by involving other local industries with symbiotic potential. Therefore, closing, as much as possible, the material cycles and implementing energy cascading by optimizing local resource use and exchange implies new type interactions between actors, each with its own motivations, which may have conflicting interests. Thus, AB modeling will be used to model their decision-making process and study these interactions that will reveal the system emergent pattern

HOW IT WORKS

The model encompasses the following entities:
1. Agents: They are the plants, represented by plant managers. In this model, 47 plants had been selected, 11 of them being already involved in a local symbiosis endeavor, the main activities are: sugar refinery, cereals and oil-seed grains agricultural cooperative, pulp and paper mills, plastics factories, cement plants, and biochemical transformation plants (Figure 1 and Figure 2)
2. Patches: They are the cells where the plants are located, each plant releases CO2 on the patch underneath it.
3. Links between agents that represent the exchange of materials: if materials (inputs and outputs) are available. Links will be created between the plants. This model uses actual quantitative input data to represent the symbiosis development, Table 2 summarizes the input and output flows for each participating plant.
4. GIS layers: Currently used as the geographic display of the roads, and the location of the plant. The plants use truck to exchange material with each other, in this model CO2 emissions from transportation is calculated using the distance between travelled during the delivery stage.

HOW TO USE IT

At every time step, each agent performs the following tasks in a chronological order:
If a pioneer plant:
1. Find a partner for exchange of material; each plant looks for an input, or more, up to the maximum of link set up by the user, among the output of the other plants. If there is availability of material that correspond to its input a link between the two entities is created, the behavior of the now partnered plant is set to 1.

  1. “Hatch” a truck: One material is found, a truck leave the plant of origin with the matching material and send to its destination using the shortest path.

If a follower plant:
• If there are more than 10 partnerships within the network: the follower plant imitates the pioneer’s behavior, which is performing steps 1, 2 and

Both breeds (pioneers and followers):
3. Remember past partnership (use link-memory): If there is availability of input, then the plants use trust transitivity algorithm; if the potential partner has a partner in common then the plant will perform a “preferential” partnership.
4. Learn and imitate the most frequent behavior within a set radius deter- mined by the user.
5. Emit CO2 during delivery
6. Calculate CO2 avoided: compare to traditional business to business delivery

THINGS TO NOTICE

(suggested things for the user to notice while running the model)

THINGS TO TRY

(suggested things for the user to try to do (move sliders, switches, etc.) with the model)

EXTENDING THE MODEL

(suggested things to add or change in the Code tab to make the model more complicated, detailed, accurate, etc.)

NETLOGO FEATURES

(interesting or unusual features of NetLogo that the model uses, particularly in the Code tab; or where workarounds were needed for missing features)

RELATED MODELS

(models in the NetLogo Models Library and elsewhere which are of related interest)

;;;Copyright 2013 by Najet BICHRAOUI. All rights reserved.
;;;No part of this model may be reproduced or transmitted in any form or
;;;by any means, electronic, photocopying, recording, or otherwise, without
;;;prior written permission of the author.

CODE

  
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;Agent-Based Modelling Scenarios for the Development of Regional Industrial Symbiosis
;;;
;;;Demonstrate the potential of an Industrial symbiosis initiative around
;;;the sugar/wheat agricultural production in the Champagne Region (France).
;;;
;;;Copyright 2013 by Najet BICHRAOUI. All rights reserved. 
;;;No part of this model may be reproduced or transmitted in any form or
;;;by any means, electronic, photocopying, recording, or otherwise, without
;;;prior written permission of the author.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


extensions [ gis nw ]
;extensions [nw]

globals  [nodes-gis InL OutL one-partner exchange partnered non-partnered factories flows_qty  nn partner-pioneer land_use symbiosis_plants_data parcels_data parcels_datatopo
          roads_data WTplants_data perimeter-dataset polyline linkwith-n2
          nodes_list paths_list exchanges-pioneer exchanges-follower partner co2_pertonne_mile mydistance_km 
          Comingto
          ComningFrom
          ]

breed [plants plant]
breed [nodes node]
breed [trucks truck]

undirected-link-breed [paths path]
undirected-link-breed [roads road]
paths-own [fid center dist iti]

directed-link-breed [partnerships partnership]
partnerships-own [
ownerFrom ownerTo
ownerFromTurt ownerToTurt
  In out 
  resource_type resource_capacity
  new-partner? route-list route-node-list mydistance dist 

   ]


trucks-own [ 
  move-list move-list2 move-index done? total_length
  to-node cur-link speed behaviour orginWho origin destinName destination
  drive routes OriLocation itinerary distances ]

nodes-own [id end? start? behaviour]

plants-own [ 
  Object_id name  plocation Industry_type trust doubt behaviour cooperation involvment
  my_potential_partners
  my_current_partner
  my_partner
  my_partnerName

  
  myresource_capacity
  plant_type Type_Capacity
  mat_received
  mat_qty_received
  mat_received_from
  mat_received_fromName
  mat_sent
  mat_qty_sent
  mat_sent_to
  mat_sent_toName
  Incount outcount Input_list Output_list Input_capacity_list Output_capacity_list Normalized_Input_list_capacity Normalized_Output_list_capacity
  out_partners_memory
  in_partners_memory
  Totalflows Input_with_qty Ouput_with_qty
  GHG_partnered GHG_nonpartnered behaviour0_tax behaviour1_tax
  MMT_Co2
  mydist_from
  mydist_to]

patches-own [Total_GHGemissions GHGemissions GHG_pioneer GHG_follower ]


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ---------- startup/setup/go ----------
to startup
  read-gis-datasets
end

to read-gis-datasets
  set symbiosis_plants_data  gis:load-dataset "data/List_plants_symb_topoVF_V1.shp"
  set perimeter-dataset      gis:load-dataset "data/departments_limites_TOPOVF.shp"
 
end

to setup-world-envelope
  let world (gis:envelope-of perimeter-dataset) ;; [ minimum-x maximum-x minimum-y maximum-y ]
  if zoom != 1 [
    let x0 (item 0 world + item 1 world) / 2          let y0 (item 2 world + item 3 world) / 2
    let W0 zoom * (item 0 world - item 1 world) / 2   let H0 zoom * (item 2 world - item 3 world) / 2
    set world (list (x0 - W0) (x0 + W0) (y0 - H0) (y0 + H0))
  ]
  gis:set-world-envelope (world)
end

to setup
  clear-all-but-globals
  import-world "data/WorldMarch20th world.csv"
  read-gis-datasets
  setup-world-envelope
  set-default-shape plants "circle"
  set-default-shape trucks "truck"
  set co2_pertonne_mile 0.00010951      ;= (0.0094 gal diesel/tonne mile) * (25,630 lbs TFC CO2 emissions/ 1000 gal) * (1 tonne / 2200 lbs)
  import-plants
  reset-ticks  
end




to import-plants
  ask patches 
  [
    set GHGemissions [] 
  ]
  
  ask plants [die]
  foreach gis:feature-list-of symbiosis_plants_data  
  [
    let location gis:location-of (first (first (gis:vertex-lists-of ?)))  
    if not empty? location 
    [
      create-plants 1 
      [
        set xcor item 0 location
        set ycor item 1 location
        set size 0.5
        set name gis:property-value ? "Name" 
        set Object_id gis:property-value ? "OBJECTID"
       
        set trust random  5
        set doubt random-float precision (0.9 + 0.5)  4
        set involvment precision (trust * doubt)      4
        
        set plocation min-one-of nodes [distance myself]           
        set Type_Capacity gis:property-value ? "Type_C"
        set Input_list []
        set Output_list []
        set Input_capacity_list []
        set Output_capacity_list []
        set myresource_capacity []
        set mat_received []
        set mat_sent []
        set flows_qty []
        
        set Input_list lput gis:property-value ? "Input1" input_list
        set Input_list lput gis:property-value ? "Input2" input_list
        set Input_list lput gis:property-value ? "Input3" input_list
        set Input_list lput gis:property-value ? "Input4" input_list
        set Input_list lput gis:property-value ? "Input5" input_list
        set Input_list lput gis:property-value ? "Input6" input_list
        set Input_list lput gis:property-value ? "Input7" input_list
        set Input_list lput gis:property-value ? "Input8" input_list
        set Input_list remove "" Input_list
        
        set Input_capacity_list lput gis:property-value ? "Input1_c" Input_capacity_list
        set Input_capacity_list lput gis:property-value ? "Input2_c" Input_capacity_list
        set Input_capacity_list lput gis:property-value ? "Input3_c" Input_capacity_list
        set Input_capacity_list lput gis:property-value ? "Input4_c" Input_capacity_list
        set Input_capacity_list lput gis:property-value ? "Input5_c" Input_capacity_list
        set Input_capacity_list lput gis:property-value ? "Input6_c2" Input_capacity_list
        set Input_capacity_list lput gis:property-value ? "Input7_c2" Input_capacity_list
        set Input_capacity_list lput gis:property-value ? "Input8_c2" Input_capacity_list
        set Input_capacity_list remove nobody Input_capacity_list
        set Input_capacity_list remove 0 Input_capacity_list
        
        Set Normalized_Input_list_capacity map [ ? / 50 ]  Input_capacity_list
        
        set Output_list lput gis:property-value ? "Output1" Output_list
        set Output_list lput gis:property-value ? "Output2" Output_list
        set Output_list lput gis:property-value ? "Output3" Output_list
        set Output_list lput gis:property-value ? "Output4" Output_list
        set Output_list lput gis:property-value ? "Output5" Output_list
        set Output_list remove "" Output_list
        
        set Output_capacity_list lput gis:property-value ? "Output1_c" Output_capacity_list
        set Output_capacity_list lput gis:property-value ? "Output2_c" Output_capacity_list
        set Output_capacity_list lput gis:property-value ? "Output3_c" Output_capacity_list
        set Output_capacity_list lput gis:property-value ? "Output4_c" Output_capacity_list
        set Output_capacity_list lput gis:property-value ? "Output5_c" Output_capacity_list
        set Output_capacity_list remove nobody Output_capacity_list
        set Output_capacity_list remove 0 Output_capacity_list
        
        Set Normalized_Output_list_capacity map [ ? / 50 ]  Output_capacity_list ;;; amount produced for the week
        
        set Incount length Input_list
        set Outcount length Output_list
        set Industry_type gis:property-value ? "TypeID" 
        
        set Totalflows sentence (Input_list)(Output_list)
        
        set Input_with_qty (map [list ?1 ?2] Input_list Normalized_Input_list_capacity )
        set Ouput_with_qty (map [list ?1 ?2] Output_list Normalized_Output_list_capacity)
        
        set MMT_Co2 gis:property-value ? "MMT_Co2"
        ask patch-here 
        [ set GHGemissions lput gis:property-value ? "MMT_Co2" GHGemissions ]
        
      ]
    ]
  ]
  
  

  ;;; setup plants ;;;
  ask plants
    [  
      ifelse (involvment > involvement_threshold_index) 
        [
          set plant_type "pioneer"
          set behaviour 1
          set GHG_partnered MMT_Co2
        ]
        [
          set plant_type "follower" 
          set behaviour 0
          set GHG_nonpartnered MMT_Co2
        ]
      check-behaviour-now
      
      ifelse (random-float 1.0 < cultural_cooperation_prob)         ;; Make plants with a frequency of cooperators determined by Cultural-coopration-prob slider contolled by the user. the higher % of cooperation the higher is likehood to get partnered         
        [set cooperation TRUE] 
        [set cooperation FALSE]  ;; if a random plant out of 20 is inferior to the initial number of coop probality, set the cooperation true, if not, set coop false    
    ]
  set factories plants

;  export-data

end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GO COMMANDS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

to go
  
  EXCHANGE_MAT
  TRANSPORT
  if learn? [learn]; 
  ask plants [ emit_GHG]
  ifelse carbon_tax? [carbon_tax] []
  if check_influence_policy? [check_influence_carbon-policy]
 ;log-turtles-tick
; file-print-csv-row
 ;export-data
;write_BSpace_output2
  tick 
  if ticks >= 100 [stop]
  
end 




;;;;==============================================================================================;;;
;;;;==============================================================================================;;;
;;;;==============================================================================================;;;


to EXCHANGE_MAT
  ask plants with [behaviour = 1]
  [
    if check_need self > 0
    [
      find_new_partner
    ]
  ]  
  find-path  ; for new partnerships
end




;;;;==============================================================================================;;;
;;;;==============================================================================================;;;
;;;;==============================================================================================;;;
;                                          find partner                                             ;



to-report check_need [plant_a]
  let x 0
  foreach needed_resources_list plant_a
  [
    set x (x + ?)
  ]
  report x
end

to-report needed_resources_list [plant_a]
  let d []
  ask plant_a
  [
    let a Input_list
    
    let b Normalized_Input_list_capacity  ;; full list of resources (capacity) needed
    let c current-input self   ;; full list of resources (capacity) got from somewhere
    
    let temp 0
    while [temp < length a]
    [
      set d lput 0 d
      set temp temp + 1
    ]
    
    set temp 0
    while [temp < length a]
    [
      let f item temp b        ;; one-of resource (capacity) need
      let g item temp c        ;; one-of received resources (capacity)
      let h (f - g)     
      set d replace-item temp d h       ;;  = index list value , replace the 0 with the number of capacity needed
      
      set temp temp + 1
    ]
  ]
  report d                     ;; report a full list about how many capacity still need to be found, full list means the length should be same as the input list.
end

to-report needed_name_list [plant_a]
  let new_need_list []
  ask plant_a
  [
    let a Input_list                   ;; full list
    let b needed_resources_list self   ;; full list
    
    let temp 0
    while [temp < length a]            ;; run a while loop with full list (length of full list)
    [
      if (item temp b > 0)
      [
        set new_need_list lput (item temp a) new_need_list
      ]
      set temp temp + 1
    ]
  ]
  report new_need_list                 ;; report a short list that all things in the list are still needed to be exchange
end

  
to-report left_resource_list [plant_a]
  let d []
  ask plant_a
  [
    let a Output_list                  ;; full list of output
    
    let b Normalized_Output_list_capacity         ;; full list of output capacity
    let c current-Output self          ;; full list of resource that were scheduled to be sent out
    
    let temp 0
    while [temp < length a]
    [
      set d lput 0 d                   ;; create a full list with the number 0
      set temp temp + 1
    ]
    
    set temp 0
    while [temp < length a]
    [
      let f item temp b                 ;; could supply
      let g item temp c                 ;; supply value that have been sent away
      let h (f - g)
      set d replace-item temp d h       ;;  = index list value , replace the 0 with the number of resource left
      
      set temp temp + 1
    ]
  ]
  report d                              ;; report a full list with the resources left, including 0 if all the resource already have been used
end

to-report left_name_list [plant_a]
  let new_left_list []
  ask plant_a
  [
    let a Output_list                                        ;; a full list
    let b left_resource_list self                            ;; a full list
    
    let temp 0
    while [temp < length a]                                  ;; while loop with full list
    [
      if (item temp b > 0)                                   ;; check if the output still not finished yet
      [
        set new_left_list lput (item temp a) new_left_list
      ]
      set temp temp + 1
    ]
  ]
  
  report new_left_list                                       ;; report a short list that all things in the list are left (still avaiable for exchange)
end

to-report current-input [plant_b]
  ; the resources that are already received (scheduled to be received)
  
  let c []
  ask plant_b
  [
    let a Input_list
    let b Input_capacity_list
    
    let temp 0
    while [temp < length a]
    [
      set c lput 0 c
      set temp temp + 1
    ]
    
    foreach sort my-in-partnerships
    [
      let d [resource_type] of ?
      let f [resource_capacity] of ?
      let g position d a             ;; index 
      let h item g c                 ;; current input capacity
      set h (h + f)
      set c replace-item g c h       ;; g c h = index list value
    ]
  ]
  report c                           ;; report a full list with how many of each resource have been scheduled to be received.
 ; set myresource_capacity resource_capacity
end

to-report current-output [plant_b]
  ; the resources that are already sent out (scheduled to be sent out)
  
  let c []
  ask plant_b
  [
    let a Output_list
    let b Normalized_Output_list_capacity
    
    let temp 0
    while [temp < length a]
    [
      set c lput 0 c
      set temp temp + 1
    ]
    
    foreach sort my-out-partnerships
    [
      let d [resource_type] of ?
      let f [resource_capacity] of ?
      let g position d a             ;; index 
      let h item g c                 ;; current output capacity list
      set h (h + f)
      set c replace-item g c h       ;; g c h = index list value
    ]
  ]
  report c                           ;; report a full list with how many of each resource have been scheduled to be sent.
  
  
end

to-report potential_partners [a_plant]
  
  ;; deal with trust transitive
  let potential_partner []
  
  ask a_plant
  [
    ifelse ((count my-in-partnerships + count my-out-partnerships) > 0)
    [

      set my_current_partner (turtle-set in-partnership-neighbors out-partnership-neighbors)
      let in_neighbors    ( [in-partnership-neighbors] of my_current_partner   with [behaviour = 1])
      let out_neighbors   ( [out-partnership-neighbors] of my_current_partner  with [behaviour = 1])
      
      ;set mat_received_from in_neighbors 
     ; set mat_received_fromName [name] of in_neighbors 
     ; set mat_sent_to out_neighbors
    ;  set mat_sent_toName [name] of out_neighbors 
      
      
      
      set out_partners_memory [name] of out-partnership-neighbors
      set in_partners_memory [name] of in-partnership-neighbors
      
      let pp_check_list1  (turtle-set my_current_partner in_neighbors out_neighbors)
      
      let pp_check_list []
      foreach sort pp_check_list1
      [
        set pp_check_list lput ? pp_check_list
      ]
      set pp_check_list   remove-duplicates pp_check_list ;; potential_partner
      set pp_check_list   remove self pp_check_list ;; potential_partner
      
      
      ifelse (not empty? pp_check_list)
      [
        set potential_partner (list_out_potential_partner pp_check_list self)
        
        if not empty? potential_partner [show "trust transitive: partner"]
        
        if empty? potential_partner
        [
          let all_other_list (list other plants with [behaviour = 1])
          set potential_partner (list_out_potential_partner all_other_list self)
          show "trust transitive: i have frd and frd of frd, they don't have what I needed"
        ]
      ]
      [
        let all_other_list (list other plants with [behaviour = 1])
        set potential_partner (list_out_potential_partner all_other_list self)
        show "trust transitive: i have no frd yet"
      ]
    ]
    [
      let all_other_list (list other plants with [behaviour = 1])
      set potential_partner (list_out_potential_partner all_other_list self)
      show "trust transitive: i have no frd yet"
    ]
  ]
  
  report potential_partner
  set my_potential_partners [name] of potential_partner
end


to-report list_out_potential_partner [a_list plant_need]
  let a_list2 turtle-set a_list
  
  let pp_list []
  let wanted_list needed_name_list plant_need
  
  foreach sort a_list2
  [
    let i_have_list left_name_list ?
    
    let x_list filter [member? ? wanted_list] i_have_list
    if not empty? x_list
    [
      set pp_list lput ? pp_list
    ]
  ] 
  
  report pp_list
  ;;
end

to-report resource_flow [plant_origin plant_destination]
  let thing ""
  let flow  0
  let thing_left left_name_list   plant_origin
  let thing_need needed_name_list plant_destination
  let capacity_left remove 0 (left_resource_list    plant_origin)
  let capacity_need remove 0 (needed_resources_list plant_destination)
 
  
  let thing_in_both_list []
  let temp 0
  while [temp < length thing_need]
  [
    let a (item temp thing_need)
    if member? a thing_left
    [
      let b item temp capacity_need
      let p position a thing_left
      let c item p capacity_left
      let f min (list b c)
      let d (list a f)                                ;;; thing (type), flow
      set thing_in_both_list lput d thing_in_both_list
    ]
    set temp temp + 1
  ]
  
  let flow_list []  
  
  foreach thing_in_both_list
  [
    let x item 1 ?
    set flow_list lput x flow_list
  ]
  
  let max_flow_possible max flow_list
  let target_thing position max_flow_possible flow_list
  
  let z item target_thing thing_in_both_list
  show z
  report z    ;;; thing (type), flow
end

to find_new_partner
  
  if (cooperation)
  [
    let pp potential_partners self      ;; a list
    let p2 turtle-set pp                ;; transform a list into an agentset
    
    ifelse (count p2 > 0) 
      [
        set one-partner one-of p2
        
        let rf resource_flow one-partner self  ;; origin --> destination
 
        create-partnership-from one-partner
        [
          if hide-part? [set hidden? true]
          set new-partner? true
          set resource_type     item 0 rf
          set resource_capacity item 1 rf
          
          set ownerFrom [name] of end1
          set ownerTo [name] of end2
           
          set ownerFromTurt end1
          set ownerToTurt end2
         
          set Comingto end2
          set ComningFrom end1
        ]            
         set my_partner one-partner
         set my_partnerName [name] of one-partner
 
         set mat_received  item 0 rf
         set mat_qty_received item 1 rf
        
         set mat_received_from my_partner
         set mat_received_fromName [name] of my_partner
         
         set flows_qty lput partnerships flows_qty
        
         ask my_partner [ 
          set mat_sent item 0 rf     
          set mat_qty_sent item 1 rf
          set mat_sent_to Comingto
          set mat_sent_toName [name] of  Comingto
                       ]
  
  ]
      [
        find_no_partner
      ]
  ]
  
end



to find_no_partner
  
  ask plants with [behaviour = 1]
  [
    if (count my-in-partnerships + count my-out-partnerships) = 0
    [
      set behaviour 0
      set color brown
    ]
  ]
  
end


;;;;==============================================================================================;;;
;;;;==============================================================================================;;;
;;;;==============================================================================================;;;
;                                           find path                                               ;



to find-path
  nw:set-snapshot nodes paths
  ask partnerships with [new-partner? = true]
  [
    let a []
    let b []
    
    let junction1 [plocation] of end1
    let junction2 [plocation] of end2
    
    let d junction2
    ask junction1
    [
      
      set a   nw:path-to            d
      set b   nw:turtles-on-path-to d
    ]
  
    set route-list      a
    set route-node-list b
  ]
  
  
  ask partnerships with [new-partner? = true]
  [
    foreach route-list
    [ask ? [set color yellow
        set dist link-length
         ]
    set mydistance sum [dist] of paths
    show mydistance
    set mydistance_km mydistance * 3
    
    ]
        ]
  
  hatch-truck
end


;;; Path length computations ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

to hatch-truck
  
  ask partnerships with [new-partner? = true]
  [    
    let m-list route-node-list
    
    ask end1
    [
      hatch-trucks 1
      [
        set size (truck-meters * 4000) / meters-per-patch
        set color green
        set move-list  m-list
        
        set done? false
        set move-index 0
        
        if hide-truck? [set hidden? true]
      ]
    ]
    
    set new-partner? false
  ]
end

to TRANSPORT
  
  moving
  
  if go-back? = true
  [ goback_command ]
end

to moving
  while [any? trucks with [done? = false]]
  [
    ask trucks with [done? = false]
    [
      ifelse (move-index) >= (length move-list)
      [
        set done? true
      ]
      [
        move-truck
      ]
    ]
  ]
  
  if all? trucks [done? = true]
    [
      ask trucks
      [
        set move-index 0
        set done? false
      ]
      show (word "plant 1 count: " count plants with [behaviour = 1])
      show (word "trucks count: "count trucks)
      show (word "partnerships count: "count partnerships)
    ]
end



to goback_command  
  ask trucks
    [
      set move-list reverse move-list
    ]
    
  moving  
  ask trucks
    [
      set move-list reverse move-list
    ]
end


to move-truck
  let x (item move-index move-list)
  face x
  fd (distance x)
  set move-index (move-index + 1)
end


;;;;==============================================================================================;;;
;;;;==============================================================================================;;;
;;;;==============================================================================================;;;
;                                         behaviour change                                          ;

to learn                                                    ;;;;;imitate most frequent behavior with turtles in radius 5
  if learn? 
  [
    ask plants with [behaviour = 0]
    [
      let a count other plants in-radius influence_radius with [behaviour = 1]
      let b count other plants in-radius influence_radius with [behaviour = 0]
      if (a + b) > 0
      [
        if (random-float ( a / (a + b) )) > (random-float b / (a + b))  ;; count a > count b
        [
          set behaviour 1
        ]
      ]
    ]
  ]
  
  check-behaviour-now
end

to check-behaviour-now
  
  ask plants
  [
    if behaviour = 1
    [set color blue]
    
    if behaviour = 0
    [set color brown]
  ]
end




;;;;==============================================================================================;;;
;;;;==============================================================================================;;;
;;;;==============================================================================================;;;
;                                          GHG calculation                                          ;

to emit_GHG
  ask plants [
    set GHG_partnered MMT_Co2 * 1.01
    set GHG_nonpartnered MMT_Co2 * 1.8
  ]
    
end



to carbon_tax ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;the contribution of C02 in GHG is considered to be 99%. water vapor is ignored. therefore GHG=Co2 
  ask plants [
    set behaviour0_tax GHG_partnered + 0 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; amount of carbon tax non-partnered plants have to pay
    set behaviour1_tax GHG_nonpartnered + 0 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; amount of carbon tax partnered plants have to pay
    ifelse (behaviour = 0) 
    [set behaviour0_tax (behaviour0_tax * carbon_tax_price)] 
    [set behaviour1_tax (behaviour1_tax * carbon_tax_price)]
  ]
end


to check_influence_carbon-policy           ;;;;;;;;;;;;;;;;;;;;;;;;;;plants managers can also change their behaviour from non-partnered to partnered through the incentive (influence) 
  ask plants [                           ;;;;;;;;;;;;;;;;;;;;;;;;; of the carbon tax. if the plant is non-partnerd and has a majority of neighboring plants that are partnered and
                                         ;;;;;;;;;;;;;;;;;;;;;;;;;; pay a certain percentage less (influence_threshold) tax, then imitate their behaviour and become partnered.
    if count plants with [behaviour1_tax = [behaviour1_tax * Influence_threshold] of myself] in-radius influence_radius > count factories with [behaviour = 0]
      [set behaviour 1]
  ]
end




;;;;;;;;;;;REPORTERS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
to clear-all-but-globals ct cp cd clear-links clear-all-plots clear-output end

to-report meters-per-patch ;; maybe should be in gis: extension?
  let world gis:world-envelope ; [ minimum-x maximum-x minimum-y maximum-y ]
  let x-meters-per-patch (item 1 world - item 0 world) / (max-pxcor - min-pxcor) * 2.59
  let y-meters-per-patch (item 3 world - item 2 world) / (max-pycor - min-pycor) * 2.59
  report mean list x-meters-per-patch y-meters-per-patch
end

to-report new-node-at [x y] ; returns a node at x,y creating one if there isn't one there.
  let n nodes with [xcor = x and ycor = y]
  ifelse any? n 
  [set n one-of n] 
  [
    create-nodes 1 
    [
      setxy x y 
      set size 0.01 
      set n self]
  ]
  report n
end

to-report total_Partnered
 report count plants with [behaviour = 1]
end

to-report total_NonPartnered
 report count plants with [behaviour = 0]
end



to-report total_qty_receiced
  report sum [mat_qty_received] of plants
end 

to-report total_qty_sent
  report sum [mat_qty_sent] of plants
end 


to-report total_qty
  report precision (total_qty_receiced + total_qty_sent) 0
end 
  
to-report Mean_trust
  report mean [trust] of plants
end

to-report Mean_doubt
  report mean [doubt] of plants
end

to-report Mean_Involvment
  report mean [involvment] of plants
end


to-report GHG_savings
  report sum [Total_GHG_nonpartnered - Total_GHG_partnered] of patches
end


to-report Tax_savings
  report sum [behaviour0_tax - behaviour1_tax] of patches
end


to-report Total_behaviour1_tax
 report sum [behaviour1_tax] of plants
end 

to-report Total_behaviour0_tax
report sum [behaviour0_tax] of plants
end 

to-report Mean_behaviour1_tax
report mean [behaviour1_tax] of plants
end 

to-report Mean_behaviour0_tax
report mean [behaviour0_tax] of plants
end 



to-report co2_transport
  report precision (co2_pertonne_mile + (total_qty * co2_pertonne_mile * mydistance_km)) 0
end

to-report Co2_transportOutside
  report precision (co2_pertonne_mile + (total_qty  * co2_pertonne_mile * (mydistance_km * random 4))) 0
  end

to-report Co2_Trans_savings
  report precision (Co2_transportOutside - co2_transport) 0
end

to-report Total_GHG_partnered
 report sum [GHG_partnered] of plants with [behaviour = 1]
end 

to-report Total_GHG_nonpartnered
report  sum [GHG_nonpartnered] of plants with [behaviour = 0]
end 


;;;;==============================================================================================;;;
;;;;==============================================================================================;;;
;;;;==============================================================================================;;;
;                                         Turtles log for individual analysis with output file                                      ;





;;;####################################